﻿using DevExpress.XtraGrid.Views.Grid;
using DXApplicationTangche.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DXApplicationTangche.UC.圣同润.merchant
{
    public partial class XianglebaUnDeliveryOrderLogisticsInfo : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
    {
        private int brandId;
        private String brandName;
        //  导入订单物流信息一览
        private List<OrderLogisticsInfoImport> orderLogistics = new List<OrderLogisticsInfoImport>();
        //  虚拟发货清单
        private List<OrderLogisticsInfoImport> virtualBillList = new List<OrderLogisticsInfoImport>();
        //  未发货订单一览
        private List<UnDeliveryOrderLogisticsInfo> unDeliveryOrderLogisticsInfos = new List<UnDeliveryOrderLogisticsInfo>();
        public XianglebaUnDeliveryOrderLogisticsInfo()
        {
            InitializeComponent();
            
            //gridviewLayout(gridViewUnDeliveryOrderLogisticsInfo, "product_name","order_sn");
            //  导入物流信息布局
            gridviewLayout(gridViewUnDeliveryOrderLogisticsInfo_1, "product_name", "order_sn");
            gridviewLayout(gridViewImportExcel,"product_name", "order_sn");

            gridViewUnDeliveryOrderLogisticsInfo.BestFitColumns();
            gridViewUnDeliveryOrderLogisticsInfo.OptionsView.BestFitMode = GridBestFitMode.Fast;

            //  历史订单布局
            bandedGridViewHistoryOrder.Columns["createdate"].GroupIndex = 0;
            bandedGridViewHistoryOrder.GroupSummary.Add(DevExpress.Data.SummaryItemType.Count, "createdate");
            //bandedGridViewHistoryOrder.GroupFormat = "{1} {2}";  //默认"{0}: [#image]{1} {2}"; 字段名称：数据 计数=？
            bandedGridViewHistoryOrder.Columns["logisticsbatchno"].GroupIndex = 1;
            //bandedGridViewHistoryOrder.GroupSummary.Add(DevExpress.Data.SummaryItemType.Count, "order_sn", bandedGridViewHistoryOrder.Columns["order_sn"]);
            //bandedGridViewHistoryOrder.GroupSummary.Add(DevExpress.Data.SummaryItemType.Count, "order_sn");
            bandedGridViewHistoryOrder.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "total_num");
            bandedGridViewHistoryOrder.GroupFormat = "{1} {2}";  //默认"{0}: [#image]{1} {2}"; 字段名称：数据 计数=？
            bandedGridViewHistoryOrder.GroupSummary[bandedGridViewHistoryOrder.GroupSummary.Count - 1].DisplayFormat = "货品数量合计：{0:N0}";


            //true 时，自定义的奇偶行颜色才有效
            this.gridViewExceptDeliveryOrder.OptionsView.EnableAppearanceEvenRow = true;
            this.gridViewExceptDeliveryOrder.OptionsView.EnableAppearanceOddRow = true;

            this.gridViewExceptDeliveryOrder.Appearance.EvenRow.BackColor = Color.LightGreen;
            this.gridViewExceptDeliveryOrder.Appearance.OddRow.BackColor = Color.LightYellow;
            this.gridViewExceptDeliveryOrder.Columns["logistics_order_time"].GroupIndex = 0;
            this.gridViewExceptDeliveryOrder.GroupSummary.Add(DevExpress.Data.SummaryItemType.Count, "order_sn");

        }

        /// <summary>
        /// gridview布局
        /// </summary>
        /// <param name="gridView"></param>
        private void gridviewLayout(DevExpress.XtraGrid.Views.Grid.GridView gridView,String groupName,String saummaryName) {
            gridView.Columns[groupName].GroupIndex = 0;
            gridView.GroupSummary.Add(DevExpress.Data.SummaryItemType.Count, groupName);
            gridView.GroupFormat = "{1} {2}";  //默认"{0}: [#image]{1} {2}"; 字段名称：数据 计数=？

            gridView.GroupSummary.Add(DevExpress.Data.SummaryItemType.Count, saummaryName, gridView.Columns[saummaryName]);
            gridView.GroupSummary[gridView.GroupSummary.Count - 1].DisplayFormat = "小计：{0:N0}";
            //gridView.OptionsBehavior.AutoExpandAllGroups = true;
        }

        private void refreshData() {
            this.gridControlUnDeliveryOrderLogisticsInfo.DataSource = this.unDeliveryOrderLogisticsInfos;
            this.gridViewUnDeliveryOrderLogisticsInfo.RefreshData();
            this.gridControlUnDeliveryOrderLogisticsInfo_1.DataSource = this.unDeliveryOrderLogisticsInfos;
            this.gridViewUnDeliveryOrderLogisticsInfo_1.RefreshData();
            this.gridControlVirtualBill.DataSource = this.virtualBillList;
            this.gridViewVirtualBill.RefreshData();
            gridViewUnDeliveryOrderLogisticsInfo_1.OptionsBehavior.AutoExpandAllGroups = true;
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            tabControl1.SelectedTab = tabPage1;
            this.unDeliveryOrderLogisticsInfos = MerchantService.getUnDeliveryOrderLogisticsInfo(this.brandId);
            refreshData();
            this.barButtonItem2.Enabled = true;
        }


        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            tabControl1.SelectedTab = tabPage1;
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.Filter = "Excel文件(*.xls)|*.xls";
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                this.gridViewUnDeliveryOrderLogisticsInfo.ExportToXls(fileDialog.FileName);
                DevExpress.XtraEditors.XtraMessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //  登出操作
            this.logout();
            try
            {
                String brandName = MerchantService.getBrandName(int.Parse(this.barEditItem1.EditValue.ToString().Trim()), this.barEditItem2.EditValue.ToString());
                if (!String.IsNullOrEmpty(brandName))
                {
                    this.brandId = int.Parse(this.barEditItem1.EditValue.ToString().Trim());
                    this.brandName = brandName;
                    this.barEditItem2.EditValue = "";
                    this.Text = this.brandName + this.Text;
                    this.barButtonItem1.Enabled = true;
                    this.barButtonItem4.Enabled = true;
                    this.barButtonItem6.Enabled = true;
                    this.barButtonItem10.Enabled = true;

                    this.button1.Enabled = true;

                    this.unDeliveryOrderLogisticsInfos = MerchantService.getUnDeliveryOrderLogisticsInfo(this.brandId);
                    refreshData();
                }
                else {
                    MessageBox.Show("用户名密码有误");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("用户名密码有误");
            }
        }

        private void barButtonItem8_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //  登出操作
            this.logout();
        }

        /// <summary>
        /// 登出操作
        /// </summary>
        private void logout() {
            this.brandId = 0;
            this.brandName = null;
            this.Text = "订单发货管理";
            this.barButtonItem1.Enabled = false;
            this.barButtonItem2.Enabled = false;
            this.barButtonItem4.Enabled = false;
            this.barButtonItem5.Enabled = false;
            this.barButtonItem6.Enabled = false;
            this.barButtonItem7.Enabled = false;
            this.button1.Enabled = false;
            this.gridControlHistoryOrder.DataSource = new List<HistoryOrder>();
            this.bandedGridViewHistoryOrder.RefreshData();
            this.virtualBillList = new List<OrderLogisticsInfoImport>();
            this.gridControlVirtualBill.DataSource = this.virtualBillList;
            this.gridViewVirtualBill.RefreshData();
            this.gridControlImportExcel.DataSource = new List<OrderLogisticsInfoImport>();
            this.gridViewVirtualBill.RefreshData();
            this.gridControlUnDeliveryOrderLogisticsInfo.DataSource = new List<UnDeliveryOrderLogisticsInfo>();
            this.gridViewUnDeliveryOrderLogisticsInfo.RefreshData();
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            tabControl1.SelectedTab = tabPage2;

            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = MIMEConst.EXCEL_MIME;
            openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            openFile.Multiselect = false;
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                DataSet result = ExcelUtil.getExcelDatas(openFile.FileName);
                if (result == null)
                {
                    return;
                }
                DataTable dataTable = result.Tables[0];

                this.orderLogistics.Clear();
                int i = 0;
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    if (i != 0) {
                        OrderLogisticsInfoImport orderLogisticsInfoImport= new OrderLogisticsInfoImport(dataRow);
                        if(!String.IsNullOrEmpty(orderLogisticsInfoImport.delivery_id))
                            this.orderLogistics.Add(orderLogisticsInfoImport);
                    }

                    i++;
                }
                this.gridControlImportExcel.DataSource = this.orderLogistics;
                this.gridViewImportExcel.RefreshData();
                gridViewImportExcel.OptionsBehavior.AutoExpandAllGroups = true;
            }
            barButtonItem5.Enabled = true;

        }

        private void gridViewUnDeliveryOrderLogisticsInfo_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                String product_name = this.gridViewUnDeliveryOrderLogisticsInfo_1.GetRowCellValue(this.gridViewUnDeliveryOrderLogisticsInfo_1.FocusedRowHandle, "product_name").ToString();

                this.textBox1.Text = product_name;
                int count = 0;
                foreach (var item in this.unDeliveryOrderLogisticsInfos)
                {
                    if (item.product_name.Equals(product_name))
                    {
                        count++;
                    }
                }
                this.textBox2.Text = count.ToString();
                this.textBox3.Focus();
            }
            catch (Exception ex)
            {

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int count = int.Parse(this.textBox3.Text);
            String product_name = this.textBox1.Text;

            List<String> orderSns = new List<String>();
            //  去掉待发货订单数据
            foreach (var item in this.unDeliveryOrderLogisticsInfos)
            {
                //  按照商品名匹配
                if (product_name.Equals(item.product_name)) {
                    if (count == 0) break;
                    this.virtualBillList.Add(
                        new OrderLogisticsInfoImport(item.order_sn, item.real_name, item.user_phone, item.user_address, item.total_num, item.payTime, item.remark, item.product_name, item.orderBaseStatus)
                        );
                    orderSns.Add(item.order_sn);
                    count--;
                }
            }
            //  增加预订单数据
            foreach (var orderSn in orderSns)
            {
                foreach (var item in this.unDeliveryOrderLogisticsInfos)
                {
                    if (orderSn.Equals(item.order_sn)) { 
                        this.unDeliveryOrderLogisticsInfos.Remove(item);
                        break;
                    }
                }
            }
            //  数据清空
            this.textBox1.Text = "";
            this.textBox2.Text = "";
            this.textBox3.Text = "";


            //  新增虚拟发货
            this.gridControlVirtualBill.DataSource = this.virtualBillList;
            this.gridViewVirtualBill.RefreshData();
            refreshData();
        }

        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            tabControl1.SelectedTab = tabPage2;
            if (this.orderLogistics.Count == 0) {
                MessageBox.Show("无物流信息上传");
                return;
            }
            List<LogisticsBody> logisticsBodies = new List<LogisticsBody>();
            foreach (var item in this.orderLogistics)
            {
                logisticsBodies.Add(item.build());
            }
            //  上传物流信息
            MerchantService.saveLogisticsBodies(this.brandId, this.brandName, logisticsBodies);
            MessageBox.Show("物流信息上传成功");
            //  刷新
            this.orderLogistics = new List<OrderLogisticsInfoImport>();
            this.gridControlImportExcel.DataSource = this.orderLogistics;
            this.gridViewImportExcel.RefreshData();
            gridViewImportExcel.OptionsBehavior.AutoExpandAllGroups = true;
            barButtonItem5.Enabled = false;
        }

        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.barButtonItem7.Enabled = true;
            tabControl1.SelectedTab = tabPage3;
            this.gridControlHistoryOrder.DataSource = MerchantService.getHistoryOrder(this.brandId);
            this.bandedGridViewHistoryOrder.RefreshData();
            bandedGridViewHistoryOrder.OptionsBehavior.AutoExpandAllGroups = true;
        }

        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            tabControl1.SelectedTab = tabPage3;
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.Filter = "Excel文件(*.xls)|*.xls";
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                this.bandedGridViewHistoryOrder.ExportToXls(fileDialog.FileName);
                DevExpress.XtraEditors.XtraMessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void barButtonItem9_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.virtualBillList.Count == 0) {
                MessageBox.Show("无预发货单");
                return;
            }
            List<String> logisticsNos = new List<string>();
            foreach (var item in this.virtualBillList)
            {
                logisticsNos.Add(item.order_sn);
            }
            //  excel导出
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.Filter = "Excel文件(*.xls)|*.xls";
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                this.gridViewVirtualBill.ExportToXls(fileDialog.FileName);
                DevExpress.XtraEditors.XtraMessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            //  虚拟发货
            MerchantService.saveVirtualLogisticsBodies(this.brandId, this.brandName, "圆通速递", "YT3562419247507", logisticsNos);
            //  刷新虚拟发货
            this.virtualBillList = new List<OrderLogisticsInfoImport>();
            this.gridControlVirtualBill.DataSource = this.virtualBillList;
            this.gridViewVirtualBill.RefreshData();
        }

        private void barButtonItem10_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            tabControl1.SelectedTab = tabPage4;
            this.unDeliveryOrderLogisticsInfos = MerchantService.getUnDeliveryOrderLogisticsInfo(this.brandId);
            //  虚拟发货视图清空
            this.virtualBillList = new List<OrderLogisticsInfoImport>();
            this.refreshData();
            this.barButtonItem9.Enabled = true;
        }

        private void accordionControlElement2_Click(object sender, EventArgs e)
        {
            this.tabControl1.SelectedTab = tabPage1;
        }

        private void accordionControlElement3_Click(object sender, EventArgs e)
        {
            this.tabControl1.SelectedTab = tabPage2;
        }

        private void accordionControlElement4_Click(object sender, EventArgs e)
        {
            this.tabControl1.SelectedTab = tabPage3;
        }

        private void accordionControlElement5_Click(object sender, EventArgs e)
        {
            this.tabControl1.SelectedTab = tabPage4;
        }

        private void accordionControlElement7_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabPage5;
            this.gridControlVirtualOrder.DataSource = MerchantService.getVirtualDeliveryOrderLogisticsInfoPage(this.brandId);
            this.gridViewVirtualOrder.RefreshData();
        }

        private void accordionControlElement8_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabPage6;
            this.gridControlExceptDeliveryOrder.DataSource = MerchantService.getExceptDeliveryOrderLogisticsInfoPage(this.brandId);
            this.gridViewExceptDeliveryOrder.RefreshData();
        }
    }
}
